package demo16_2;

//用双链表实现队列
public class MyQueue {
    static class ListNode {
        private int val;
        private ListNode next;
        private ListNode prev;

        public ListNode(int val) {
            this.val = val;
        }
    }
    private ListNode front;//队头
    private ListNode rear;//队尾
    private int usedSize;

    //放数据  头插法
    public void offer(int data) {
        ListNode node = new ListNode(data);
        if (front == null) {
            front = rear = node;
            usedSize++;
            return;
        }
        node.next = front;
        front.prev = node;
        front = node;
        usedSize++;
    }
    //出队列 相当于删除最后一个节点
    public int poll() {
        if (front == null) {
            return -1;
        }
        int data = rear.val;
        if (front == rear) {
            front = null;
            rear = null;
            usedSize--;
            return data;
        }
        rear = rear.prev;
        rear.next = null;
        usedSize--;
        return data;
    }

    public int peek() {
        if (front == null) {
            return -1;
        }
        return rear.val;
    }

    public int size() {
        return usedSize;
    }

    public Boolean isEmpty() {
        return usedSize == 0;
    }
}
